import csv
from pyecharts import options as opts
from pyecharts.charts import Bar

#从 CSV 文件中读取豆瓣新片榜电影评分数据，并用 pyecharts 绘制柱状图，输出为 HTML 页面
# 读取 CSV 文件中的数据
def read_csv_data(csv_path):
    data = []
    try:
        with open(csv_path, 'r', encoding='utf-8-sig') as csv_file:
            reader = csv.DictReader(csv_file)
            for row in reader:
                data.append(row)
    except Exception as e:
        print(f"读取 CSV 文件时出错: {e}")
    return data

# 使用 pyecharts 绘制柱状图
def draw_bar_chart(data):
    # 提取电影中文名和评分数据
    movie_names = []
    ratings = []
    for row in data:
        movie_names.append(row['影片中文名'])
        rating = row['评分']
        if rating:
            ratings.append(float(rating))
        else:
            ratings.append(0)

    # 创建柱状图对象
    bar = (
        Bar()
        .add_xaxis(movie_names)
        .add_yaxis("评分", ratings)
        .set_global_opts(
            title_opts=opts.TitleOpts(title="豆瓣新片榜电影评分"),
            toolbox_opts=opts.ToolboxOpts(is_show=True),
            xaxis_opts=opts.AxisOpts(axislabel_opts={"rotate": 45}),
            yaxis_opts=opts.AxisOpts(name="评分")
        )
    )

    # 渲染图表到 HTML 文件
    bar.render("../templates/movie_ratings.html")

if __name__ == "__main__":
    CSV_PATH = "../豆瓣新片榜.csv"
    # 读取数据
    movie_data = read_csv_data(CSV_PATH)
    if movie_data:
        # 绘制图表
        draw_bar_chart(movie_data)
        print("图表已成功渲染到 movie_ratings.html")